<?php

namespace plugin\cms\app\bll;

use Exception;
use plugin\cms\app\validate\Rewrite as ValidateRewrite;
use support\Db;
use Throwable;

/**
 * URL重写
 */
class Rewrite
{

    /**
     * 查询使用中的伪静态规则
     *
     * @return array
     */
    public function findByUse(): array
    {
        $table = Db::table('cms_rewrite')
            ->where('use', '=', 1)
            ->first();
        return $table === null ? [] : get_object_vars($table);
    }

    /**
     * 查询所有伪静态规则
     *
     * @return array
     */
    public function select(): array
    {
        return Db::table('cms_rewrite')
            ->get()
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();
    }

    /**
     * Undocumented function
     *
     * @param integer $id
     * @return void
     */
    public function setUse(int $id, int $use)
    {
        Db::beginTransaction();
        try {

            Db::table('cms_rewrite')
                ->update([
                    'use' => 0
                ]);
            Db::table('cms_rewrite')
                ->where('id', '=', $id)
                ->update([
                    'use' => $use
                ]);
            Db::commit();
        } catch (Throwable $e) {
            Db::rollBack();
            throw $e;
        }
    }

    public  function add(array $data)
    {
        $validateRewrite = new ValidateRewrite();
        if (!$validateRewrite->check($data)) {
            throw new Exception($validateRewrite->getSimpleError());
        }

        return Db::table('cms_rewrite')
            ->insert($data);
    }

    public function delete(int $id)
    {
        return Db::table('cms_rewrite')
            ->where('id', '=', $id)
            ->delete();
    }
}
